package com.chenyue.cm.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenyue.cm.base.aop.Log;
import com.chenyue.cm.base.bean.Pageable;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.utils.RequestUtil;
import com.chenyue.cm.common.utils.StringUtil;
import com.chenyue.cm.user.dao.JdThirdInformationMapper;
import com.chenyue.cm.user.domain.JdAppUser;
import com.chenyue.cm.user.domain.JdAppUserExample;
import com.chenyue.cm.user.domain.JdThirdInformation;
import com.chenyue.cm.user.domain.JdUserInvite;
import com.chenyue.cm.user.domain.vo.JdAppUserPlatformVo;
import com.chenyue.cm.user.service.JdAppUserService;
import com.chenyue.cm.user.service.JdUserInviteService;
import com.chenyue.cm.user.vo.ThirdUser;
import com.chenyue.cm.utils.DateUtils;
import com.chenyue.cm.utils.MD5Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * @author chenyue-cm
 * @date 2021-07-20
 */
@RestController
@RequestMapping("/jdAppUser")
public class JdAppUserController {

    private final JdAppUserService jdAppUserService;

    private final JdUserInviteService jdUserInviteService;


    private final JdThirdInformationMapper thirdInformationMapper;

    public JdAppUserController(JdAppUserService jdAppUserService,
                               JdUserInviteService jdUserInviteService, @Qualifier("jdThirdInformationMapper") JdThirdInformationMapper thirdInformationMapper) {
        this.jdAppUserService = jdAppUserService;
        this.jdUserInviteService = jdUserInviteService;
        this.thirdInformationMapper = thirdInformationMapper;
    }

//    @RequestMapping("/getList")
//    public Success getList(HttpServletRequest request) {
//        Pageable pageInfo = RequestUtil.getPageable(request);
//        PageVo<JdAppUser> result = jdAppUserService.getPageBean(pageInfo, JdAppUser.class);
//        return Success.success(result);
//    }

    @RequestMapping("/getList")
    public Success getList(HttpServletRequest request) {
        Pageable pageInfo = RequestUtil.getPageable(request);
        //设置分页信息
        PageHelper.startPage(pageInfo.getPageIndex(), pageInfo.getPageSize(), true);
        LambdaQueryWrapper<JdAppUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(JdAppUser::getId,0);
        Map<String, Object> pageSearch = pageInfo.getPageSearch();
        if (pageSearch != null) {
            if (null != pageSearch.get("SEARCH_LIKE_user_name")) {
                wrapper.like(JdAppUser::getUserName, String.valueOf(pageSearch.get("SEARCH_LIKE_user_name")));
            }
            if (null != pageSearch.get("SEARCH_EQ_mobile")) {
                wrapper.like(JdAppUser::getMobile, String.valueOf(pageSearch.get("SEARCH_EQ_mobile")));
            }
        }
        List<JdAppUser> list = jdAppUserService.list(wrapper);
        if(list != null && list.size()>0){
            for (JdAppUser jdAppUser : list) {
                if(StringUtils.isNotBlank(jdAppUser.getInviteCode())){
                    jdAppUser.setInviteCode(this.getUserInviteCode(jdAppUser.getInviteCode(),jdAppUser.getId().toString()));
                }
            }
        }
        //封装返回结果
        PageInfo<JdAppUser> result = new PageInfo<>(list);

        return Success.success(result);
    }

    @RequestMapping("/getExportList")
    public Success getExportList(HttpServletRequest request) {
        Pageable pageInfo = RequestUtil.getPageable(request);
        LambdaQueryWrapper<JdAppUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(JdAppUser::getId,0);
        Map<String, Object> pageSearch = pageInfo.getPageSearch();
        if (pageSearch != null) {
            if (null != pageSearch.get("SEARCH_LIKE_user_name")) {
                wrapper.like(JdAppUser::getUserName, String.valueOf(pageSearch.get("SEARCH_LIKE_user_name")));
            }
            if (null != pageSearch.get("SEARCH_EQ_mobile")) {
                wrapper.like(JdAppUser::getMobile, String.valueOf(pageSearch.get("SEARCH_EQ_mobile")));
            }
        }
        List<JdAppUser> list = jdAppUserService.list(wrapper);
        return Success.success(list);
    }

    @RequestMapping("/getUserInfo")
    public Success getUserInfo(HttpServletRequest request) {
        String userId = request.getParameter("userId");
        QueryWrapper<JdAppUser> wrapper = new QueryWrapper<>();
        wrapper.eq("id", userId);
        List<JdAppUser> list = jdAppUserService.list(wrapper);
        return Success.success(list);
    }

    /**
     * @param vo 插入实体
     * @return Success
     */
    @Log
    @RequestMapping("/save")
    public Success save(JdAppUser vo) {
        vo.setLastLoginTime(Calendar.getInstance().getTime());
        vo.setUserNum(jdAppUserService.getUserNum());
        vo.setUserName(StringUtil.convertStr(vo.getMobile(), 4, 3, vo.getMobile().length() - 4));
        String salt = StringUtil.getSalt();
        vo.setPassword(MD5Util.getMD5(vo.getPassword() + salt, false, 32));
        vo.setRegisterTime(DateUtils.getToday());
        boolean success = jdAppUserService.save(vo);
        return success ? Success.success() : Success.error();
    }

    /**
     * @param vo      修改实体
     * @param request id
     * @return Success
     */
    @Log
    @RequestMapping("/edit")
    public Success edit(JdAppUser vo, HttpServletRequest request) {
        String id = request.getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            vo.setUserName(StringUtil.convertStr(vo.getMobile(), 4, 3, vo.getMobile().length() - 4));
            String salt = vo.getSalt();
            vo.setPassword(MD5Util.getMD5(vo.getPassword() + salt, false, 32));
            int success = jdAppUserService.getBaseMapper().updateById(vo);
            return success > 0 ? Success.success() : Success.error();
        } else {
            return Success.error("id不能为空");
        }
    }

    /**
     * @param id 主键
     * @return Success
     */
    @Log
    @RequestMapping("/delete/{id}")
    public Success deleteByPrimaryKey(@PathVariable("id") Integer id) {
        JdAppUserExample aExample = new JdAppUserExample();
        aExample.createCriteria().andIdEqualTo(id);
        int success = jdAppUserService.deleteByExample(aExample);
        return success > 0 ? Success.success() : Success.error();
    }

    /**
     * 【API】----  删除多个数据
     *
     * @return Success
     */
    @Log
    @RequestMapping("/delete")
    public Success delete(String ids) {
        String[] idStrings = ids.split(",");
        for (String idString : idStrings) {
            int success = jdAppUserService.deleteByPrimaryKey(idString);
            if (success == 0) {
                return Success.error();
            }
        }
        return Success.success();
    }

    @Log
    @RequestMapping("/getThirdList")
    public Success getThirdList() {
        List<ThirdUser> list = new ArrayList<>();
        LambdaQueryWrapper<JdThirdInformation> wrapper = new LambdaQueryWrapper<>();
        List<JdThirdInformation> jdThirdInformationList = thirdInformationMapper.selectList(wrapper);
        for (JdThirdInformation jdThirdInformation : jdThirdInformationList) {
            ThirdUser thirdUser = new ThirdUser();
            thirdUser.setId(jdThirdInformation.getUserId());
            final JdAppUser third = jdAppUserService.getById(jdThirdInformation.getUserId());
            if (third == null) {
                continue;
            }
            thirdUser.setName(third.getUserName());
            list.add(thirdUser);
        }
        boolean isAddAdmin = true;
        if(list.size()>0){
            for (ThirdUser thirdUser : list) {
                if(thirdUser.getId() == 0){
                    isAddAdmin = false;
                    break;
                }
            }
        }
        if(isAddAdmin){
            ThirdUser thirdUser = new ThirdUser();
            thirdUser.setId(0);
            thirdUser.setName("管理人员");
            list.add(thirdUser);
        }
        return Success.success(list);
    }

    /**
     * @param vo 平台信息添加
     * @return Success
     */
    @Log
    @RequestMapping("/savePlatform")
    public Success savePlatform(JdAppUserPlatformVo vo) {
        JdAppUser platformUser = jdAppUserService.getById(0);
        if(platformUser != null){
            return Success.error("平台信息已经存在,不可以重复添加");
        }
        //添加平台得用户名和头像信息
        JdAppUser jdAppUser = new JdAppUser();
        jdAppUser.setUserName(vo.getUserName());
        jdAppUser.setHeadImg(vo.getHeadImg());
        jdAppUser.setRegisterTime(DateUtils.getToday());
        boolean jdAppUserSuccess = jdAppUserService.save(jdAppUser);
        //添加平台详细信息 简介和风采
        JdThirdInformation jdThirdInformation = new JdThirdInformation();
        jdThirdInformation.setUserId(0);
        jdThirdInformation.setBanner(vo.getBanner());
        jdThirdInformation.setThirdDetails(vo.getThirdDetails());
        jdThirdInformation.setThirdIntroduction(vo.getThirdIntroduction());
        jdThirdInformation.setCt(Calendar.getInstance().getTime());
        int thirdInformationInsert = thirdInformationMapper.insert(jdThirdInformation);
        if(jdAppUserSuccess && thirdInformationInsert>0){
            return Success.success();
        }
        return Success.error();
    }

    /**
     * @param vo 平台信息编辑
     * @return Success
     */
    @Log
    @RequestMapping("/editPlatform")
    public Success editPlatform(JdAppUserPlatformVo vo,HttpServletRequest request) {
        String id = request.getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            //编辑平台信息
            JdAppUser jdAppUser = new JdAppUser();
            jdAppUser.setId(Integer.valueOf(id));
            jdAppUser.setUserName(vo.getUserName());
            jdAppUser.setHeadImg(vo.getHeadImg());
            int success = jdAppUserService.getBaseMapper().updateById(jdAppUser);
            //编辑平台详情
            int thirdInformationUpdate = 0;
            if(vo.getThirdId() == null){
                thirdInformationUpdate = 1;
            }else{
                JdThirdInformation jdThirdInformation = new JdThirdInformation();
                jdThirdInformation.setId(vo.getThirdId());
                jdThirdInformation.setUserId(0);
                jdThirdInformation.setBanner(vo.getBanner());
                jdThirdInformation.setThirdDetails(vo.getThirdDetails());
                jdThirdInformation.setThirdIntroduction(vo.getThirdIntroduction());
                thirdInformationUpdate = thirdInformationMapper.updateById(jdThirdInformation);
            }
            return success > 0 &&  thirdInformationUpdate>0 ? Success.success() : Success.error();
        } else {
            return Success.error("id不能为空");
        }
    }

    /**
     *  平台信息列表
     * @param request
     * @return
     */
    @RequestMapping("/getPlatformList")
    public Success getPlatformList(HttpServletRequest request) {
        Pageable pageInfo = RequestUtil.getPageable(request);
        //设置分页信息
        PageHelper.startPage(pageInfo.getPageIndex(), pageInfo.getPageSize(), true);
        LambdaQueryWrapper<JdAppUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JdAppUser::getId, 0);
        List<JdAppUser> list = jdAppUserService.list(wrapper);
        List<JdAppUserPlatformVo> jdAppUserPlatformVos = new ArrayList<>();
        JdAppUserPlatformVo jdAppUserPlatformVo = new JdAppUserPlatformVo();
        if(list != null && list.size()>0){
            //用户信息
            JdAppUser jdAppUser = list.get(0);
            jdAppUserPlatformVo.setId(Integer.valueOf(jdAppUser.getId()));
            jdAppUserPlatformVo.setUserName(jdAppUser.getUserName());
            jdAppUserPlatformVo.setHeadImg(jdAppUser.getHeadImg());
            //详情信息
            LambdaQueryWrapper<JdThirdInformation> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(JdThirdInformation::getUserId, 0);
            List<JdThirdInformation> jdThirdInformationList = thirdInformationMapper.selectList(wrapper1);
            if(jdThirdInformationList != null && jdThirdInformationList.size()>0){
                if(jdThirdInformationList.get(0) != null){
                    JdThirdInformation thirdInformation = jdThirdInformationList.get(0);
                    jdAppUserPlatformVo.setThirdId(thirdInformation.getId());
                    jdAppUserPlatformVo.setUserId(thirdInformation.getUserId());
                    jdAppUserPlatformVo.setBanner(thirdInformation.getBanner());
                    jdAppUserPlatformVo.setThirdIntroduction(thirdInformation.getThirdIntroduction());
                    jdAppUserPlatformVo.setThirdDetails(thirdInformation.getThirdDetails());
                    jdAppUserPlatformVo.setCt(thirdInformation.getCt());
                }
            }
        }
        jdAppUserPlatformVos.add(jdAppUserPlatformVo);
        //封装返回结果
        PageInfo<JdAppUserPlatformVo> result = new PageInfo<>(jdAppUserPlatformVos);
        return Success.success(result);
    }


    private String getUserInviteCode(String inviteCode,String userId) {
        LambdaQueryWrapper<JdUserInvite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JdUserInvite::getInviteCode,inviteCode);
        wrapper.eq(JdUserInvite::getReceiveUser,userId);
        List<JdUserInvite> list = jdUserInviteService.list(wrapper);
        if(list != null && list.size()>0){
            JdUserInvite jdUserInvite = list.get(0);
            int sendUser = jdUserInvite.getSendUser();
            if(sendUser != 0){
                JdAppUser jdAppUser = jdAppUserService.getById(sendUser);
                if(jdAppUser != null){
                    return jdAppUser.getMobile();
                }
            }
        }
        //封装返回结果
        return "";
    }
}
